package com.osdp.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.osdp.common.constant.CommonConstant;
import com.osdp.common.util.ConvertUtil;
import com.osdp.common.util.MD5Util;
import com.osdp.sc.dto.PermissionDTO;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

public class PermissionDataUtil {
    /**
     * 智能处理错误数据，简化用户失误操作
     *
     * @param permission
     */
    public static PermissionDTO intelligentProcessData(PermissionDTO permission) {
        if (permission == null) {
            return null;
        }

        // 组件
        if (ConvertUtil.isNotEmpty(permission.getComponent())) {
            String component = permission.getComponent();
            if (component.startsWith("/")) {
                component = component.substring(1);
            }
            if (component.startsWith("views/")) {
                component = component.replaceFirst("views/", "");
            }
            if (component.startsWith("src/views/")) {
                component = component.replaceFirst("src/views/", "");
            }
            if (component.endsWith(".vue")) {
                component = component.replace(".vue", "");
            }
            permission.setComponent(component);
        }

        // 请求URL
        if (ConvertUtil.isNotEmpty(permission.getUrl())) {
            String url = permission.getUrl();
            if (url.endsWith(".vue")) {
                url = url.replace(".vue", "");
            }
            if (!url.startsWith("http") && !url.startsWith("/") && !url.trim().startsWith("{{")) {
                url = "/" + url;
            }
            permission.setUrl(url);
        }

        // 一级菜单默认组件
        if (CommonConstant.FLAG_ZERO_0 == permission.getPermsType() && ConvertUtil.isEmpty(permission.getComponent())) {
            // 一级菜单默认组件
            permission.setComponent("layouts/RouteView");
        }
//        permission.setTenantId(LoginUserContext.getLoginUser().getTenantId());
        return permission;
    }

    /**
     * 如果没有index页面 需要new 一个放到list中
     *
     * @param metaList
     */
    public static void addIndexPage(List<PermissionDTO> metaList) {
        boolean hasIndexMenu = false;
        for (PermissionDTO sysPermission : metaList) {
            if (PermissionDTO.FRONT_PAGE.equals(sysPermission.getPermsName())) {
                hasIndexMenu = true;
                break;
            }
        }
        if (!hasIndexMenu) {
            metaList.add(0, new PermissionDTO(true));
        }
    }


    public static void getPermissionJsonArray(JSONArray jsonArray, List<PermissionDTO> metaList, JSONObject parentJson) {
        for (PermissionDTO permission : metaList) {
            if (permission.getPermsType() == null) {
                continue;
            }
            String parentId = permission.getParentId();
            JSONObject json = getPermissionJsonObject(permission);
            if (json == null) {
                continue;
            }
            if (parentJson == null && ConvertUtil.isEmpty(parentId)) {
                jsonArray.add(json);
                if (!permission.isLeaf()) {
                    getPermissionJsonArray(jsonArray, metaList, json);
                }
            } else if (parentJson != null && ConvertUtil.isNotEmpty(parentId)
                    && parentId.equals(parentJson.getString("id"))) {
                // 类型( 0：一级菜单 1：子菜单 2：按钮 )
                if (permission.getPermsType() == CommonConstant.FLAG_TWO_2) {
                    JSONObject metaJson = parentJson.getJSONObject("meta");
                    if (metaJson.containsKey("permissionList")) {
                        metaJson.getJSONArray("permissionList").add(json);
                    } else {
                        JSONArray permissionList = new JSONArray();
                        permissionList.add(json);
                        metaJson.put("permissionList", permissionList);
                    }
                    // 类型( 0：一级菜单 1：子菜单 2：按钮 )
                } else if (permission.getPermsType() == CommonConstant.FLAG_ONE_1
                        || permission.getPermsType() == CommonConstant.FLAG_ZERO_0) {
                    if (parentJson.containsKey("children")) {
                        parentJson.getJSONArray("children").add(json);
                    } else {
                        JSONArray children = new JSONArray();
                        children.add(json);
                        parentJson.put("children", children);
                    }

                    if (!permission.isLeaf()) {
                        getPermissionJsonArray(jsonArray, metaList, json);
                    }
                }
            }

        }
    }

    public static JSONObject getPermissionJsonObject(PermissionDTO permission) {
        JSONObject json = new JSONObject();
        // 类型(0：一级菜单 1：子菜单 2：按钮)
        if (permission.getPermsType() == CommonConstant.FLAG_TWO_2) {
            //json.put("action", permission.getPerms());
            //json.put("type", permission.getPermsType());
            //json.put("describe", permission.getName());
//            return null;
        } else if (permission.getPermsType() == CommonConstant.FLAG_ZERO_0
                || permission.getPermsType() == CommonConstant.FLAG_ONE_1) {
            json.put("id", permission.getId());
            json.put("name",permission.getPermsName());
            json.put("parentId",permission.getParentId());
//            if (permission.isRoute()) {
//                json.put("route", "1");// 表示生成路由
//            } else {
//                json.put("route", "0");// 表示不生成路由
//            }
            if (isWWWHttpUrl(permission.getUrl())) {//外网地址
                json.put("path", MD5Util.MD5Encode(permission.getUrl(), "utf-8"));
            } else {
                json.put("path", permission.getUrl());
            }
            // 重要规则：路由name (通过URL生成路由name,路由name供前端开发，页面跳转使用)
//            if (ConvertUtil.isNotEmpty(permission.getComponentName())) {
//                json.put("name", permission.getComponentName());
//            } else {
//                json.put("name", urlToRouteName(permission.getUrl()));
//            }
            // 是否隐藏路由，默认都是显示的
//            if (permission.isHidden()) {
//                json.put("hidden", true);
//            }
            // 聚合路由
//            if (permission.isAlwaysShow()) {
//                json.put("alwaysShow", true);
//            }
            json.put("component", permission.getComponent());
            if (ConvertUtil.isNotEmpty(permission.getIcon())) {
                json.put("icon", permission.getIcon());
            }
            JSONObject meta = new JSONObject();
            // 默认所有的菜单都加路由缓存，提高系统性能
            meta.put("keepAlive", "true");
            meta.put("title", permission.getPermsName());
//            if (ConvertUtil.isEmpty(permission.getParentId())) { // 父ID为空，一级菜单为重定向
//                // 一级菜单跳转地址
////                json.put("redirect", permission.getRedirect());
//                if (ConvertUtil.isNotEmpty(permission.getIcon())) {
//                    meta.put("icon", permission.getIcon());
//                }
//            } else {
//                if (ConvertUtil.isNotEmpty(permission.getIcon())) {
//                    meta.put("icon", permission.getIcon());
//                }
//            }
            if (isWWWHttpUrl(permission.getUrl())) {
                meta.put("url", permission.getUrl());
            }
            json.put("meta", meta);
        }

        return json;
    }


    /**
     * 判断是否外网URL 例如： http://localhost:8080/boot/swagger-ui.html#/ 支持特殊格式： {{
     * window._CONFIG['domianURL'] }}/druid/ {{ JS代码片段 }}，前台解析会自动执行JS代码片段
     *
     * @return
     */
    public static boolean isWWWHttpUrl(String url) {
        if (url != null && (url.startsWith("http://") || url.startsWith("https://") || url.startsWith("{{"))) {
            return true;
        }
        return false;
    }

    public static String urlToRouteName(String url) {
        if (ConvertUtil.isNotEmpty(url)) {
            if (url.startsWith("/")) {
                url = url.substring(1);
            }
            url = url.replace("/", "-");

            // 特殊标记
            url = url.replace(":", "@");
            return url;
        } else {
            return null;
        }
    }

    /**
     * 获取权限JSON数组
     *
     * @param jsonArray
     * @param metaList
     */
    private void getAuthJsonArray(JSONArray jsonArray, List<PermissionDTO> metaList) {
        for (PermissionDTO permission : metaList) {
            if (permission.getPermsType() == null) {
                continue;
            }
            JSONObject json = null;
            if (permission.getPermsType() == CommonConstant.FLAG_TWO_2 ) { //&& "1".equals(permission.getStatus())
                json = new JSONObject();
                json.put("action", permission.getPermsCode());// 权限编码
                json.put("type", permission.getPermsType());
                json.put("describe", permission.getPermsName());
                jsonArray.add(json);
            }
        }
    }
    //--------------------------------------------------
    public JSONObject getPermissionByUserId(String userId) {
        if(StringUtils.isEmpty(userId)){
            return null;
        }
        List<PermissionDTO> metaList = null; //permissionService.queryPermissionsByUserId(userId);
        PermissionDataUtil.addIndexPage(metaList); // 添加首页
        JSONObject json = new JSONObject();
        JSONArray menujsonArray = new JSONArray();
        PermissionDataUtil.getPermissionJsonArray(menujsonArray, metaList, null);

        JSONArray authjsonArray = new JSONArray();
        this.getAuthJsonArray(authjsonArray, metaList);
        //所有按钮
        List<PermissionDTO> allAuthList = null; //permissionService.queryPermissionAllButton();
        JSONArray allauthjsonArray = new JSONArray();
        this.getAllAuthJsonArray(allauthjsonArray, allAuthList);

        json.put("menu", menujsonArray);
        json.put("auth", authjsonArray);
        json.put("allAuth", allauthjsonArray);
        return json;
    }
    /**
     * 获取权限JSON数组
     *
     * @param jsonArray
     */
    private void getAllAuthJsonArray(JSONArray jsonArray, List<PermissionDTO> allList) {
        JSONObject json = null;
        for (PermissionDTO permission : allList) {
            json = new JSONObject();
            json.put("action", permission.getPermsCode());
//            json.put("status", permission.getStatus());
            json.put("type", permission.getPermsType());
            json.put("describe", permission.getPermsName());
            jsonArray.add(json);
        }
    }
}
